// 封装axios
/* 1.简化代码 2.换掉axios更加简单 */
import axios from 'axios'
import { ref } from 'vue'
import { CONFIG } from '../config/index.js'
import router from '../router/index.js'
import { ElMessage,ElLoading } from 'element-plus'

let loadingInstance = ref()  //全局loadding
//请求拦截器
axios.interceptors.request.use(function (config) {
    loadingInstance.value = ElLoading.service({ // 请求时开启loading
        text: "玩命加载中...",
        background: 'rgba(0,0,0,0.1)'  // 颜色
    })
    // 在发送请求之前做些什么
    console.log("请求拦截器:", config)  
    // 添加时间戳到请求中
    if ( config.method == 'get' ) {
        // 解决缓存
        let timeStamp = (new Date()).getTime()  // 打印时间戳
        console.log(timeStamp)
        if (config.params) {
        config.params.timeStamp = timeStamp
      }else {
        config.params = {
          timeStamp: timeStamp
        }
      }
    }
    let tokenValue = ""
    try {
        tokenValue = window.localStorage.getItem(CONFIG.TOKEN_NAME)
    } catch (error) {
        tokenValue = ""
    }
    if (tokenValue == "" || tokenValue == null) {
        config.headers[CONFIG.TOKEN_NAME] = ""
    }else {
        config.headers[CONFIG.TOKEN_NAME] = tokenValue
    }
    return config;
  }, function (error) {
    ElMessage({
        message: "请求错误:" + error.message,
        type: "error"
    })
    return Promise.reject(error);
  })

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 判断响应状态码是否正常
    console.log("response",response)
    if (response.data.status == 200) {
        loadingInstance.value.close() // 关闭loading
        return Promise.resolve(response)
    }else if(response.data.status == 401){ //token失效删除token
        ElMessage({
            message: response.data.message,
            type: "warning"
        })
        window.localStorage.removeItem(CONFIG.TOKEN_NAME)
        router.currentRoute.path != "/login" && router.replace("/login") //跳转登录页
        loadingInstance.value.close() // 关闭loading
    }else {
        ElMessage({
            message: response.data.message,
            type: "warning"
        })
        loadingInstance.value.close() // 关闭loading
        // return Promise.reject(error);
    }
    return response;
  }, function (error) {
    ElMessage({
        message: "请求错误:" + error.message,
        type: "error"
    })
    loadingInstance.value.close()
    return Promise.reject(error);
  })

const request = (url='', data={}, method='get', timeout=5000) => {
    console.log('使用封装函数去处理请求')
    return new Promise((resolve, reject) => {
        console.log("使用axios请求接口")
        const methodLower = method.toLowerCase()
        if (methodLower === 'get') {
            axios({
                method: methodLower,
                params: data,
                timeout: timeout,
                url: url
            }).then((response) => {
                resolve(response)
            }).catch((error) => {
                reject(error)
            })
        }else if (methodLower === 'post') {
            axios({
                method: methodLower,
                data: data,
                timeout: timeout,
                url: url
            }).then((response) => {
                resolve(response)
            }).catch((error) => {
                reject(error)
            })
        }
    })
}

export default request